#include "Timer.h"

std::list<Timer*> 	Timer::timerList;

Timer::Timer(){
	state = STOPPED;
	targetTime = 0;
	ticks = 0;	
}
Timer::~Timer(){

}
void Timer::Set(unsigned int target_time){
	targetTime = ticks = target_time;
} 
int Timer::GetRemainingTime(){
	return ticks;
}	
int Timer::Reset(){
	ticks = targetTime;
	return ticks;
}	
int Timer::Reset(unsigned int new_target_time){
	Set(new_target_time);
	ticks = targetTime;
	return ticks;
}
bool Timer::Tick(){
	if(ticks <= 0)
		return true;
	else{
		ticks--;
		return false;
	}
}
int Timer::Start(){
	state = RUNNING;
	return ticks;
}
int Timer::Stop(){
	state = STOPPED;
	return ticks;
}
int Timer::Pause(unsigned int pause_time){
	ticks += abs(pause_time);
	return ticks;
}	

Timer* Timer::GetTimer(int number){
	if(number < 0) 
		number = 0;
	int n = 0;
	std::list<Timer*>::iterator iter = timerList.begin();
    while(iter != timerList.end()){
       if(n == number) 
		   return (*iter);
	   else{ 
		   n++;
		   iter++;
	   }
    }
	//if not found, create timer and return that
	
	return FactoryTimer();
}

Timer* Timer::FactoryTimer(){
	Timer* new_timer = new Timer();
	timerList.push_back(new_timer);
	return timerList.back();
}
void Timer::Deinitialize(){
	if(this != NULL)
	state = DEAD;
}
void Timer::UpdateAllTimers(){
	std::list<Timer*>::iterator iter = timerList.begin();	
    while (iter != timerList.end()){		
		if ((*iter)->state == RUNNING){
			(*iter)->Tick();
			iter++;
		}
		else if( (*iter)->state == DEAD){
			delete (*iter);			
            iter = timerList.erase( iter );	//iterator = next element location
        }
		
    }
}
bool Timer::Arrived(){
	if( ticks <= 0 ) return true;
	else return false;
}
unsigned int Timer::GetTimerListSize(){
	return timerList.size();
}